<template>
  <div class="product-detail">
    <div class="detail-content" v-if="detail">
      <van-nav-bar title="商品详情页" left-arrow @click-left="$router.back()" />
      <!-- 图片播放区域 -->
      <div class="img-play-area">
        <van-swipe class="my-swipe" ref="swipe" @change="onChange" :autoplay="isSwipe">
          <van-swipe-item class="img-box" v-for="item in goodsImages" :key="item.file_id" @click="previewImg" v-model="show">
            <img :src="item.external_url" alt="">
          </van-swipe-item>
        </van-swipe>
        <!-- 自定义指示器是和轮播图分离的，否则会一直移动! 子绝父相 -->
        <div class="custom-indicator">{{ current + 1 }}/ {{goodsImages.length}}</div>
      </div>

      <div class="product-info" v-if="detail.goods_price_min">
        <div class="product-price clearfix">
          <div class="sale-price"><span class="small">￥</span>{{detail.goods_price_min}}</div>
          <span class="origin-price" v-if="detail.line_price_min">￥{{detail.line_price_min}}</span>
          <span class="sale-count">已售{{detail.goods_sales}}件</span>
        </div>

        <div class="product-title">
          {{detail.goods_name}}
        </div>
      </div>
      <!-- 保障服务 -->
      <div class="service" @click="showPannel = true">
        <div class="left" v-for="item in guaranteeList" :key="item.service_id">
          <img src="@/assets/good-service.png" alt="">
          <span>{{item.name}}</span>
        </div>

        <div class="right">
          <van-icon name="arrow" class="icon-arrow"></van-icon>
        </div>
      </div>

      <div class="product-commend" v-if="comment_list.length > 0">
        <div class="left">
          <span>商品评价({{ total }}条)</span>
        </div>

        <div class="right" @click="$jumpToPath('comment/index', { goodsId: goodsId })">
          <span class="more">查看更多</span>
          <van-icon name="arrow" class="icon-arrow"></van-icon>
        </div>
      </div>

      <!-- 评价内容 -->
      <div class="commend-list" v-for="item in comment_list" :key="item.comment_id" style="margin: 10px;padding:10px 17px;">
        <div class="commend-header">
          <img :src="item.user.avatar_url" alt="" v-if="item.user.avatar_url">
          <img v-else src="@/assets/default-avatar.png" alt="">

          <span class="number" v-if="item.user.nick_name">{{item.user.nick_name}}</span>
          <van-rate v-if="item.score === 10" :value="5" class="rate" :size="25" color="#ffd21e" void-icon="star" void-color="#eee" />
          <van-rate v-else-if="item.score === 20" :value="3" class="rate" :size="25" color="#ffd21e" void-icon="star" void-color="#eee" />
          <van-rate v-else :value="1" class="rate" :size="25" color="#ffd21e" void-icon="star" void-color="#eee" />
        </div>

        <div class="commend-content">
          {{item.content}}
        </div>
        <div class="date">{{item.create_time}}</div>
      </div>

      <!-- 图片列表 -->
      <van-cell>
        商品描述
      </van-cell>
      <van-list>
        <div class="det-content" v-html="detail.content"></div>
      </van-list>
    </div>

    <van-goods-action class="product-footer">
      <van-goods-action-icon icon="wap-home-o" text="首页" to="/pages/home" />
      <van-goods-action-icon to="/pages/cart/index" icon="cart-o" :badge="cartTotal" v-if="cartTotal > 0">购物车</van-goods-action-icon>
      <van-goods-action-icon to="/pages/cart/index" icon="cart-o" v-else>购物车</van-goods-action-icon>
      <van-goods-action-button type="danger" text="加入购物车" @click="showCart = true; action = 'cart' " />
      <van-goods-action-button color="#ffb800" text="立即购买" @click="showCart = true; action = 'order'" />
    </van-goods-action>

    <!--服务模块 -->
    <van-action-sheet v-model="showPannel" title="服务">
      <div class="service-content clearfix" v-for="item in guaranteeList" :key="item.service_id">
        <div class="service-left">
          <img src="@/assets/good-service.png" alt="">
        </div>
        <div class="service-right">
          <h5>{{item.name}}</h5>
          <div class="customer-service">
            {{item.summary}}
          </div>
        </div>
      </div>
    </van-action-sheet>

    <!-- 购物车面板 -->
    <CartPannel @open="setCartState(true)" :visable="showCart" :detail="detail" @close="setCartState($event)">
      <template #cart-footer>
        <div class="cart-footer" v-if="action === 'cart'">
          <van-button v-if="detail.skuList[0].stock_num > 0" color="#f9432f" round block type="info" class="cart_btn" @click="addCart()">加入购物车</van-button>
          <van-button v-else round block disabled color="#ccc" class="cart_btn">该商品已抢完</van-button>
        </div>
        <div class="cart-footer" v-else>
          <van-button v-if="detail.skuList[0].stock_num > 0" color="#ffb800" round block type="info" class="cart_btn" @click="buyNow()">立即购买</van-button>
          <van-button v-else round block disabled color="#ccc" class="cart_btn">该商品已抢完</van-button>
        </div>
      </template>
    </CartPannel>
  </div>
</template>

<script>
import CartPannel from '@/components/CartPannel'
import { ImagePreview, Dialog, Toast } from 'vant'
import { getProdcutGuaranteeService, getCommentLimit, getProductDetail } from '@/apis/product'
import { getCartTotal } from '@/apis/cart'
import { mapState, mapMutations } from 'vuex'
export default {
  components: {
    CartPannel
  },
  name: 'ProductDetail',
  data () {
    return {
      current: 1,
      show: false,
      showPannel: false,
      index: 0,
      action: 'cart',
      // 多组件共享detail对象
      detail: {},
      goodsImages: [],
      // 保障服务
      guaranteeList: [],
      comment_list: [],
      total: 0
    }
  },
  computed: {
    // 显示购物车面板
    showCart: {
      get () {
        return this.$store.state.cart.showCart
      },
      set (newValue) {
        this.setCartState(newValue)
      }
    },
    // 是否登录
    isLogin () {
      return this.$store.state.user.token
    },
    // 动态宽度
    isSwipe () {
      return !this.show ? 3000 : 0
    },
    goodsId () {
      console.log(this.$route.query.goodsId)
      return this.$route.query.goodsId
    },
    previewImages () {
      console.log(this.goodsImages)
      return this.goodsImages.map((item) => item.preview_url)
    },
    goodsSkuId () {
      return this.detail.skuList[0].goods_sku_id
    },
    ...mapState('cart', ['cartTotal', 'goodsNum']),
    cartTotal: {
      get () {
        return this.$store.state.cart.cartTotal
      },
      set (value) {
        this.$store.state.cart.cartTotal = value
      }
    }
  },
  async created () {
    this.getProductDetail(+this.goodsId)
    this.getProdcutGuaranteeService()
    this.getCartTotal()
    this.getCommentLimit({ goodsId: this.goodsId, limit: 2 })
  },
  methods: {
    ...mapMutations('cart', ['setCartState']),
    onChange (index) {
      this.current = index
    },
    previewImg () {
      // console.log(this.$refs.swipe._props.autoplay)
      ImagePreview({
        images: this.previewImages,
        closeable: true,
        // startPosition: this.index,
        showIndicators: true,
        closeOnPopstate: true,
        touchable: true
      })
    },
    // 请求数据
    async getProdcutGuaranteeService () {
      const res = await getProdcutGuaranteeService(this.goodsId)
      const { list } = res.data
      this.guaranteeList = list
    },
    // 获取评价列表
    async getCommentLimit (params) {
      const res = await getCommentLimit(params)
      const { data: { list, total } } = res
      this.comment_list = list
      this.total = total
    },
    // 获取购物车总数
    async getCartTotal () {
      const { data: { cartTotal } } = await getCartTotal()
      this.cartTotal = cartTotal
    },
    async getProductDetail (params) {
      const { data: detail } = await getProductDetail(params)
      this.detail = detail.detail
      this.goodsImages = detail.detail.goods_images
    },
    addCart () {
      debugger
      if (!this.isLogin) {
        debugger
        // 可以用代码混入
        Dialog.confirm({
          title: '温馨提示',
          message: '此时此刻需要您登陆喔~',
          confirmButtonColor: '#258dff',
          confirmButtonText: '去登录',
          cancelButtonText: '再逛会'
        })
          .then(() => {
            //  在跳转之前把showCart状态保存，回来的时候才会有对应的显示购物车面板
            this.$jumpToPath('user/login')
            this.setCartState(true)
          })
          .catch(() => {
            // on cancel
            this.setCartState(false)
            this.$router.back()
          })
      } else {
        console.log(this.goodsNum)
        // 已经登录，可以调用接口，加入购物车
        this.$store.dispatch('cart/AsyncAddCart', {
          goodsId: this.detail.skuList[0].goods_id,
          goodsNum: this.goodsNum,
          goodsSkuId: this.goodsSkuId
        })
        Toast('加入购物车成功')
        this.setCartState(false)
      }
    },
    buyNow () {
      this.$jumpToPath('orderCheck', { mode: 'buyNow', goodsId: this.detail.skuList[0].goods_id, goodsNum: this.goodsNum, goodsSkuId: this.goodsSkuId })
    }
  }
}
</script>
<style lang="less" scoped>
.small {
  font-size: 13px;
}
.product-detail {
  .detail-content {
    background-color: #fafafa;
    height: 637px;
    overflow: auto;
    .img-play-area {
      position: relative;
    }
  }

  // 底部导航
  .product-footer {
    // bottom: -70px;
    .van-goods-action-button {
      border-radius: 999px;
      margin: 0px 5px;
    }
  }

  .product-info {
    padding: 17px;
    .product-price {
      height: 50px;
      line-height: 50px;
      color: #a49a95;
      .sale-price {
        float: left;
        margin: 0px 10px;
        font-size: 23px;
        color: #fa2209;
      }
      .origin-price {
        float: left;
        font-size: 16px;
        color: #a49a95;
        text-decoration: line-through;
      }
      .sale-count {
        float: right;
      }
    }

    .product-title {
      margin: 5px 0px;
    }
  }

  .detail-content::-webkit-scrollbar {
    width: 0.5rem;
    background-color: transparent;
  }

  // 服务
  .service {
    height: 60px;
    line-height: 60px;
    padding: 12px 17px 12px 0px;
    .left {
      float: left;

      img {
        margin: 4px 6px 6px 12px;
        width: 30px;
        height: 30px;
        vertical-align: middle;
      }
    }
    .right {
      float: right;
      height: 45px;
      line-height: 65px;

      .icon-arrow {
        color: #000;
        font-size: 24px;
      }
    }
  }

  .service-content {
    padding: 10px 15px;

    .service-left {
      float: left;
      padding-top: 5px;
      height: 100px;
      width: 60px;
    }

    .service-right {
      float: left;
      width: 250px;

      h5 {
        height: 35px;
        font: normal 400 20px/35px '微软雅黑';
      }
      .customer-service {
        font-size: 18px;
        color: rgb(112, 109, 109);
      }
    }
  }

  // 商品评价
  .product-commend {
    padding: 10px 17px;
    height: 50px;
    line-height: 50px;

    .left {
      float: left;
    }
    .right {
      float: right;
      .more {
        color: #a49a95;
        margin: 0px 10px;
      }
    }
  }

  // 评价内容
  .commend-list {
    background-color: #fff;
    margin: 10px 0;
    padding: 0px 40px;
    // height: 80px;
    // line-height: 80px;
    img {
      width: 50px;
      height: 50px;
      border-radius: 25px;
      vertical-align: middle;
    }
    .number {
      margin: 0px 20px;
      color: #a49a95;
      font-size: 20px;
    }
    .rate {
      margin-right: 10px;
    }
    .date {
      height: 20px;
      line-height: 20px;
      color: #b0c1d1;
    }

    .commend-content {
      margin: 10px;
    }
  }
}
// 轮播图播放区域
.my-swipe {
  width: 350px;
  height: 400px;
  margin: 0 auto;
}
.my-swipe .van-swipe-item {
  text-align: center;
  width: 350px;
  height: 400px;
}
.custom-indicator {
  z-index: 100;
  position: absolute;
  right: 0;
  bottom: 25px;
  padding: 5px 10px;
  border-radius: 15px;
  font-size: 12px;
  background: rgba(0, 0, 0, 0.1);
}

.img-box {
  img {
    // width: 400px;
    // height: 400px;
    width: 100%;
    height: 100%;
  }
}

.det-content {
  ::v-deep img {
    // width: 100%;
    max-width: 375px;
  }
}

.cart_btn {
  border: 0;
}

.van-cell__value {
  font-size: 23px;
}
.van-action-sheet__header {
  height: 20px;
  font-size: 0px;
  color: #ffffff;
}
</style>
